﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

namespace YanZhiwei.DotNet3._5.Utilities.Common
{
    /// <summary>
    /// 图片帮助类
    /// </summary>
    public static class ImageHelper
    {
        /// <summary>
        /// 将BitmapSource转换成Bitmap
        /// </summary>
        /// <param name="bitmapSource">BitmapSource</param>
        /// <returns>Bitmap</returns>
        public static Bitmap ToBitmap(this BitmapSource bitmapSource)
        {
            BmpBitmapEncoder _encoder = new BmpBitmapEncoder();
            _encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            using (var stream = new MemoryStream())
            {
                _encoder.Save(stream);
                return new Bitmap(new Bitmap(stream));
            }
        }
        /// <summary>
        /// 将Bitmap转换成BitmapImage
        /// </summary>
        /// <param name="bitmap">Bitmap</param>
        /// <returns>BitmapImage</returns>
        public static BitmapImage ToBitmapImage(this Bitmap bitmap)
        {
            MemoryStream _stream = new MemoryStream();
            bitmap.Save(_stream, ImageFormat.Png);

            BitmapImage _bitmapImage = new BitmapImage();
            _bitmapImage.BeginInit();
            _bitmapImage.StreamSource = _stream;

            _bitmapImage.EndInit();
            _stream.Close();

            return _bitmapImage;
        }
        /// <summary>
        /// 将byte[]转换成BitmapImage
        /// </summary>
        /// <param name="byteArray"> byte[] </param>
        /// <returns>BitmapImage</returns>

        public static BitmapImage ToBitmapImage(this byte[] byteArray)
        {
            MemoryStream _stream = new MemoryStream(byteArray);
            BitmapImage _bitmap = new BitmapImage();
            _bitmap.BeginInit();
            _bitmap.StreamSource = _stream;
            _bitmap.EndInit();

            return _bitmap;
        }

        /// <summary>
        /// 将byep[]转换成BitmapSource
        /// </summary>
        /// <param name="byteArray">byte[]</param>
        /// <returns>BitmapSource</returns>
        public static BitmapSource ToBitmapSource(this byte[] byteArray)
        {
            MemoryStream _stream = new MemoryStream(byteArray);
            PngBitmapDecoder _decoder = new PngBitmapDecoder(_stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource _bitmapSource = _decoder.Frames[0];
            return _bitmapSource;
        }
    }
}
